package com.jinlejia.erp.ui.access_manager;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.freedom.yefeng.yfrecyclerview.YfListMode;
import com.freedom.yefeng.yfrecyclerview.YfLoadMoreListener;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.NewHouseAccessAdapter;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.common.WrapContentLinearLayoutManager;
import com.jinlejia.erp.databinding.FragmentHand2Binding;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.utils.DateUtil;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

public class NewHouseAccessFragment extends Fragment  implements OnDateSetListener, YfLoadMoreListener
        , SwipeRefreshLayout.OnRefreshListener{
    private View view;

    private long millis;
    private int page = 1;
    private NewHouseAccessAdapter adapter;
    private boolean mLoadingLock = false;

    public NewHouseAccessFragment() {
        // Required empty public constructor
    }
    private FragmentHand2Binding binding;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_hand2, null);
            binding = DataBindingUtil.bind(view);
            binding.preBtn.setOnClickListener(this::onViewClicked);
            binding.date.setOnClickListener(this::onViewClicked);
            binding.nextBtn.setOnClickListener(this::onViewClicked);
            initView();
            getData();
        }
        // 缓存的rootView需要判断是否已经被加过parent，
        // 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {
            parent.removeView(view);
        }
        binding = DataBindingUtil.bind(view);
        binding.preBtn.setOnClickListener(this::onViewClicked);
        binding.date.setOnClickListener(this::onViewClicked);
        binding.nextBtn.setOnClickListener(this::onViewClicked);
        return view;
    }

    private void initView() {
        millis = System.currentTimeMillis();
        binding.date.setText(DateUtil.getDateWeek(millis));
        binding.refreshLayout.setColorSchemeResources(R.color.yellow, R.color.light_yellow);
        binding.refreshLayout.setOnRefreshListener(this);
        binding.recyclerView.setLayoutManager(new WrapContentLinearLayoutManager(getContext()));
        binding.recyclerView.enableAutoLoadMore(this);
        adapter = new NewHouseAccessAdapter(new ArrayList<Map<String, Object>>());
        binding.recyclerView.setAdapter(adapter);
        adapter.changeMode(YfListMode.MODE_LOADING);

    }

    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.pre_btn:
                millis = DateUtil.previousDay(millis);
                binding.date.setText(DateUtil.getDateWeek(millis));
                getData();
                break;
            case R.id.date:
                TimePickerDialog calendarPicker = new TimePickerDialog.Builder()
                        .setType(Type.YEAR_MONTH_DAY)
                        .setTitleStringId("选择时间")
                        .setCurrentMillseconds(millis)
                        .setThemeColor(getResources().getColor(R.color.yellow))
                        .setWheelItemTextNormalColor(getResources().getColor(R.color.hintColor))
                        .setWheelItemTextSelectorColor(getResources().getColor(R.color.yellow))
                        .setCallBack(this)
                        .build();
                calendarPicker.show(getFragmentManager(), "year_month_date");
                break;
            case R.id.next_btn:
                millis = DateUtil.nextDay(millis);
                binding.date.setText(DateUtil.getDateWeek(millis));
                getData();
                break;
        }
    }

    @Override
    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
        millis = millseconds;
        binding.date.setText(DateUtil.getDateWeek(millseconds));
        getData();
    }

    private void getData() {
        binding.refreshLayout.setRefreshing(true);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("accessTime", DateUtil.getTime(millis, "yyyy-MM-dd"));
        jsonObject.put("pageIndex", page);
        jsonObject.put("pageSize", 10);
        OkHttpUtils.postString().url(ApiConfig.NEW_HOUSE_ACCESS_LIST)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        call.cancel();
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(getContext(), response, adapter)) {
                            JSONArray data = JSON.parseArray(response.get("data").toString());
                            ArrayList<Map<String, Object>> dataList = JSON.parseObject(data.toJSONString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            if (page == 1) {
                                adapter.setData(dataList);
                            } else {
                                adapter.addData(dataList);
                            }
                        }
                        if (binding.refreshLayout.isRefreshing())
                            binding.refreshLayout.setRefreshing(false);
                        mLoadingLock = false;
                    }
                });

    }

    @Override
    public void onRefresh() {
        page = 1;
        getData();
    }

    @Override
    public void loadMore() {
        if (mLoadingLock) {
            return;
        }
        mLoadingLock = true;
        page++;
        getData();
    }
}
